<template>
  <div class="user-edit-container">
    <!-- Header 区域 -->
    <van-nav-bar
      title="编辑资料"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <!-- 用户资料 -->
    <van-cell-group class="action-card">
      <van-cell title="头像" is-link center>
        <template #default>
          <!-- 虚拟点击，让文件上传框隐藏，并设置ref属性，点击图片片时触发input文件框点击事件上传文件，上传完后，在input的change事件中获取上传的图片文件 -->
          <van-image
            round
            class="avatar"
            :src="profile.photo"
            @click="$refs.iptFile.click()"
          />
          <input
            type="file"
            ref="iptFile"
            v-show="false"
            accept="image/*"
            @change="onChangeFn"
          />
        </template>
      </van-cell>
      <van-cell
        title="名称"
        is-link
        :value="profile.name"
        @click="showNameDialogFn"
      />
      <van-cell
        title="性别"
        is-link
        :value="profile.gender === 1 ? '男' : '女'"
      />
      <van-cell title="生日" is-link :value="profile.birthday" @click="showBirthFn"/>
    </van-cell-group>
    <van-dialog
      title="修改名称"
      show-cancel-button
      v-model="isShowNameDialog"
      :before-close="onNameDialogBeforeClose"
    >
      <van-field
        v-model.trim="userName"
        input-align="center"
        maxlength="7"
        placeholder="请输入名称"
        v-focus
      />
    </van-dialog>
    <van-popup v-model="isShowBirth" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="isShowBirth = false"
        @confirm="changeBirthFn"
      />
    </van-popup>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { Notify } from 'vant'
import { getProfileApi, updatePhotoApi, updateFielApi } from '@/api'
export default {
  name: 'UserEdit',
  data () {
    return {
      profile: {},
      isShowNameDialog: false,
      userName: '',
      isShowBirth: false,
      currentDate: new Date(),
      minDate: new Date(1900, 0, 1),
      maxDate: new Date()
    }
  },
  async created () {
    const res = await getProfileApi()
    this.profile = res.data.data
    // console.log(res)
  },
  methods: {
    async changeBirthFn () {
      // console.log(dayjs(this.currentDate).format('YYYY-MM-DD'))
      await updateFielApi({
        birthday: dayjs(this.currentDate).format('YYYY-MM-DD')
      })
      this.profile.birthday = dayjs(this.currentDate).format('YYYY-MM-DD')
      this.isShowBirth = false
    },
    showBirthFn () {
      this.isShowBirth = true
      this.currentDate = this.profile.birthday
    },
    async onChangeFn (ev) {
      // console.log(ev.target.files[0])
      // 判断是否上传数据
      if (ev.target.files.length === 0) return
      // new创建表单对象实例，
      const fd = new FormData()
      // 并将上传的表单文件，添加到表单对象实例中
      fd.append('photo', ev.target.files[0])
      // console.dir(fd)
      const res = await updatePhotoApi(fd)
      this.profile.photo = res.data.data.photo
      // console.log(res)

      // 解决缓存第二中方法，更换头像后，返回用户页面，头像不更新  可以在vuex中利用数据动态绑定，来完成及时更新
      this.$store.commit('updatePhoto', res.data.data.photo)
    },
    showNameDialogFn () {
      this.isShowNameDialog = true
      this.userName = this.profile.name
    },
    async onNameDialogBeforeClose (action, done) {
      // action的值: confirm或cancel(点击按钮区分)
      if (action === 'confirm') {
        // 确定
        // unicode编码 \u4092
        // url编码 %E2%C3%D1
        if (/^[A-Za-z0-9\u4e00-\u9fa5]{1,7}$/.test(this.userName)) {
          await updateFielApi({ uaerName: this.userName })
          this.profile.name = this.userName
          done()
        } else {
          // 提示用户
          Notify({ type: 'warning', message: '用户名中英文和数字1-7位' })
          // 输入不符合规则，提示用户，并且不关闭弹窗
          done(false)
        }
      } else {
        done()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.user-edit-container {
  padding-top: 46px;
  .avatar {
    width: 50px;
    height: 50px;
  }
}
</style>
